﻿using DataProvider;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Model;
using Newtonsoft.Json;
using Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Utility;

namespace api.Controllers.Resource
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class Resource_BenchController : ControllerBase
    {
        public IActionResult GetInitData()
        {
            var ResponserList = Sys_UserProvider.Instances.GetUserListAll().Select(x => new { x.Id, x.RealName });
            var DataSourceList = Sys_DataSourceProvider.Instances.GetListBySourceId(new List<int>() { 4,1 });
            var AreaList = DataSourceList.FindAll(x => x.SourceId == 1).Select(x=>new { x.Id,x.SourceName});
            var BenchTypeList = DataSourceList.FindAll(x => x.SourceId == 4).Select(x => new { x.Id, x.SourceName });
            var jsonData = new {
                ResponserList= ResponserList,
                AreaList= AreaList,
                BenchTypeList= BenchTypeList
            };
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = jsonData }));
        }
        public IActionResult GetList(LayPageModel param)
        {
            int pageSize = Convert.ToInt32(param.limit), pageIndex = Convert.ToInt32(param.page);
            int pageNum = (pageIndex - 1) * pageSize;
            string condition = " Status=0 ";
            if (!string.IsNullOrEmpty(param.searchKey))
            {
                condition = condition + string.Format(@" and (BenchNo like '%{0}%' 
or BenchName like '%{0}%' 
or KeyParam like '%{0}%'
or BenchModel like '%{0}%'
or Remark like '%{0}%'
) ", param.searchKey);
            }
            var queryParam = param.searchJson.ToJObject();
            if (!queryParam["BenchType"].IsEmpty())
            {
                condition = condition + " and BenchType="+ queryParam["BenchType"].ToString()+" ";
            }
            var treeSearchJson = param.treeSearchJson;
            if (!treeSearchJson.IsEmpty()) 
            {

                 
            }
            var List = Resource_BenchService.Instances.QueryCustom(condition);
            var Count = List.Count;
            var ParamList = List.Skip(pageNum).Take(pageSize).ToList();
            var UserDic = Sys_UserProvider.Instances.GetUserListAll().ToDictionary(x => x.Id);
            foreach (var d in ParamList)
            {
                d.CreateUserName = UserDic.ContainsKey(d.CreateUser) ? UserDic[d.CreateUser].RealName : "";
                d.ResponserName= UserDic.ContainsKey(d.Responser) ? UserDic[d.Responser].RealName   : "";
            }
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { data = ParamList, count = Count }));
        }
        public IActionResult GetTreeData()
        {
            var BenchTypeList = Sys_DataSourceProvider.Instances.GetListBySourceId(new List<int>() { 4 });
            var treelist = new List<LayTreeModel>();
            var PDataEnt = new LayTreeModel() { id = 0, title = "TestBenchType", children = new List<LayTreeModel>(), spread=true };

            foreach (var d in BenchTypeList)
            {
                PDataEnt.children.Add(new LayTreeModel() { id = d.Id, title = d.SourceName, children = new List<LayTreeModel>(), spread = false });
            }
            treelist.Add(PDataEnt);
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = treelist }));
        }
        public IActionResult GetDetail(CommonId param)
        {
            var Ent = Resource_BenchService.Instances.GetEntity(param.Id);
            if(Ent==null)
            {
                return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = -1, data = "Get Data Error! Please Retry After Refresh Broswer" }));
            }
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = Ent }));
        }
        public IActionResult Save(CommonSaveModel param)
        {
            var userToken = (UserCache)JwtHelp.GetToken(HttpContext.Request.Headers["Authorization"].ToString()).data; ;
            var Ent = JsonConvert.DeserializeObject<Resource_Bench>(param.strEntity);
            if (Ent.Id == 0)
            {
                Ent.CreateUser = userToken.UserId;
                Ent.CreateTime = DateTime.Now;
                Resource_BenchService.Instances.Add(userToken.UserId, Ent);
            }
            else
            {
                Ent.LastUpdateTime = DateTime.Now;
                Ent.LastUpdateUser = userToken.UserId;
                Resource_BenchService.Instances.Edit(userToken.UserId, Ent);
            }
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = Ent }));
        }
        public IActionResult GetBenchCheckItemList(CommonId param)
        {
            var List = Resource_BenchCheckListService.Instances.QueryCustom(" Status=0 and BenchId="+param.Id.ToString());

            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { data = List, code=0 }));
        }
        public IActionResult SaveBenchCheckItem(CommonSaveModel param)
        {
            var userToken = (UserCache)JwtHelp.GetToken(HttpContext.Request.Headers["Authorization"].ToString()).data; ;
            var Ent = JsonConvert.DeserializeObject<Resource_BenchCheckList>(param.strEntity);
            if (Ent.Id == 0)
            {
                Ent.CreateUser = userToken.UserId;
                Ent.CreateTime = DateTime.Now;
                Resource_BenchCheckListService.Instances.Add(userToken.UserId, Ent);
            }
            else
            {
                Ent.LastUpdateTime = DateTime.Now;
                Ent.LastUpdateUser = userToken.UserId;
                Resource_BenchCheckListService.Instances.Edit(userToken.UserId, Ent);
            }
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = "Success" }));
        }
    }
}
